import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../core/theme/app_colors.dart';
import '../../core/theme/app_text_styles.dart';
import '../../core/constants/app_constants.dart';
import '../../core/constants/emotion_constants.dart';
import '../../core/utils/app_utils.dart';
import '../../controllers/analytics_controller.dart';
import '../layouts/main_layout.dart';

/// 趋势分析页面 - 显示情绪数据的统计分析
/// Analysis Page - Display statistical analysis of emotion data
class AnalysisPage extends StatelessWidget {
  const AnalysisPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<AnalyticsController>(
      init: AnalyticsController(),
      builder: (controller) {
        return MainLayout(
          currentIndex: 2,
          appBarTitle: '趋势分析',
          child: RefreshIndicator(
            onRefresh: controller.refreshData,
            child: SingleChildScrollView(
              padding: EdgeInsets.all(16.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 时间范围选择器 / Time range selector
                  _buildTimeRangeSelector(controller),
                  
                  const SizedBox(height: AppConstants.spacingLarge),
                  
                  // 统计概览 / Statistics overview
                  _buildStatisticsOverview(controller),
                  
                  SizedBox(height: 24.h),
                  
                  // 情绪趋势图 / Emotion trend chart
                  _buildEmotionTrendChart(controller),
                  
                  SizedBox(height: 24.h),
                  
                  // 情绪分布图 / Emotion distribution chart
                  _buildEmotionDistributionChart(controller),
                  
                  SizedBox(height: 24.h),
                  
                  // 强度分布图 / Intensity distribution chart
                  _buildIntensityDistributionChart(controller),
                  
                  SizedBox(height: 24.h),
                  
                  // 词云分析 / Word cloud analysis
                  _buildWordCloudSection(controller),
                  
                  SizedBox(height: 24.h),
                  
                  // 详细统计 / Detailed statistics
                  _buildDetailedStatistics(controller),
                ],
              ),
            ),
          ),
        );
      }
    );
  }

  /// 构建时间范围选择器
  /// Build time range selector
  Widget _buildTimeRangeSelector(AnalyticsController controller) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '分析时间范围',
            style: AppTextStyles.titleMedium,
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          Row(
            children: [
              Expanded(
                child: _buildTimeRangeChip(
                  controller,
                  '7天',
                  7,
                  controller.selectedDays == 7,
                ),
              ),
              const SizedBox(width: AppConstants.spacingSmall),
              Expanded(
                child: _buildTimeRangeChip(
                  controller,
                  '30天',
                  30,
                  controller.selectedDays == 30,
                ),
              ),
              const SizedBox(width: AppConstants.spacingSmall),
              Expanded(
                child: _buildTimeRangeChip(
                  controller,
                  '90天',
                  90,
                  controller.selectedDays == 90,
                ),
              ),
              const SizedBox(width: AppConstants.spacingSmall),
              Expanded(
                child: _buildTimeRangeChip(
                  controller,
                  '全部',
                  -1,
                  controller.selectedDays == -1,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建时间范围选择芯片
  /// Build time range selection chip
  Widget _buildTimeRangeChip(
    AnalyticsController controller,
    String label,
    int days,
    bool isSelected,
  ) {
    return GestureDetector(
      onTap: () => controller.setTimeRange(days),
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: AppConstants.paddingMedium,
          vertical: AppConstants.paddingSmall,
        ),
        decoration: BoxDecoration(
          color: isSelected ? AppColors.primary : AppColors.background,
          borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
          border: Border.all(
            color: isSelected ? AppColors.primary : AppColors.border,
          ),
        ),
        child: Text(
          label,
          style: AppTextStyles.bodyMedium.copyWith(
            color: isSelected ? AppColors.onPrimary : AppColors.textPrimary,
            fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  /// 构建统计概览
  /// Build statistics overview
  Widget _buildStatisticsOverview(AnalyticsController controller) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '统计概览',
            style: AppTextStyles.titleMedium,
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          Row(
            children: [
              Expanded(
                child: _buildStatCard(
                  '总记录数',
                  '${controller.statisticsSummary?.totalRecords ?? 0}',
                  Icons.edit_note,
                  AppColors.primary,
                ),
              ),
              const SizedBox(width: AppConstants.spacingMedium),
              Expanded(
                child: _buildStatCard(
                  '平均强度',
                  (controller.statisticsSummary?.averageIntensity ?? 0.0).toStringAsFixed(1),
                  Icons.trending_up,
                  AppColors.secondary,
                ),
              ),
            ],
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          Row(
            children: [
              Expanded(
                child: _buildStatCard(
                  '最常情绪',
                  controller.statisticsSummary?.mostCommonEmotion ?? '无',
                  Icons.favorite,
                  AppColors.accent,
                ),
              ),
              const SizedBox(width: AppConstants.spacingMedium),
              Expanded(
                child: _buildStatCard(
                  '记录天数',
                  '${controller.statisticsSummary?.totalRecords ?? 0}',
                  Icons.calendar_today,
                  AppColors.info,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建统计卡片
  /// Build statistics card
  Widget _buildStatCard(
    String title,
    String value,
    IconData icon,
    Color color,
  ) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Column(
        children: [
          Icon(
            icon,
            color: color,
            size: 24,
          ),
          const SizedBox(height: AppConstants.spacingSmall),
          Text(
            value,
            style: AppTextStyles.titleLarge.copyWith(
              color: color,
              fontWeight: FontWeight.bold,
            ),
          ),
          Text(
            title,
            style: AppTextStyles.bodySmall.copyWith(
              color: AppColors.textSecondary,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  /// 构建情绪趋势图
  /// Build emotion trend chart
  Widget _buildEmotionTrendChart(AnalyticsController controller) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '情绪趋势',
            style: AppTextStyles.titleMedium,
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          SizedBox(
            height: 200,
            child: controller.emotionTrends.isEmpty
                ? _buildEmptyChart('暂无趋势数据')
                : LineChart(
                    LineChartData(
                      gridData: FlGridData(
                        show: true,
                        drawVerticalLine: false,
                        horizontalInterval: 2,
                        getDrawingHorizontalLine: (value) {
                          return FlLine(
                            color: AppColors.border,
                            strokeWidth: 1,
                          );
                        },
                      ),
                      titlesData: FlTitlesData(
                        leftTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            interval: 2,
                            getTitlesWidget: (value, meta) {
                              return Text(
                                value.toInt().toString(),
                                style: AppTextStyles.bodySmall.copyWith(
                                  color: AppColors.textSecondary,
                                ),
                              );
                            },
                          ),
                        ),
                        bottomTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            interval: 1,
                            getTitlesWidget: (value, meta) {
                              final index = value.toInt();
                              if (index >= 0 && index < controller.emotionTrends.length) {
                                return Text(
                                  AppUtils.formatShortDate(
                                    controller.emotionTrends[index].date,
                                  ),
                                  style: AppTextStyles.bodySmall.copyWith(
                                    color: AppColors.textSecondary,
                                  ),
                                );
                              }
                              return const SizedBox();
                            },
                          ),
                        ),
                        rightTitles: const AxisTitles(
                          sideTitles: SideTitles(showTitles: false),
                        ),
                        topTitles: const AxisTitles(
                          sideTitles: SideTitles(showTitles: false),
                        ),
                      ),
                      borderData: FlBorderData(
                        show: true,
                        border: Border.all(
                          color: AppColors.border,
                          width: 1,
                        ),
                      ),
                      minX: 0,
                      maxX: (controller.emotionTrends.length - 1).toDouble(),
                      minY: 0,
                      maxY: 10,
                      lineBarsData: [
                        LineChartBarData(
                          spots: controller.emotionTrends
                              .asMap()
                              .entries
                              .map((entry) => FlSpot(
                                    entry.key.toDouble(),
                                    entry.value.averageIntensity,
                                  ))
                              .toList(),
                          isCurved: true,
                          color: AppColors.primary,
                          barWidth: 3,
                          isStrokeCapRound: true,
                          dotData: FlDotData(
                            show: true,
                            getDotPainter: (spot, percent, barData, index) {
                              return FlDotCirclePainter(
                                radius: 4,
                                color: AppColors.primary,
                                strokeWidth: 2,
                                strokeColor: AppColors.surface,
                              );
                            },
                          ),
                          belowBarData: BarAreaData(
                            show: true,
                            color: AppColors.primary.withOpacity(0.1),
                          ),
                        ),
                      ],
                    ),
                  ),
          ),
        ],
      ),
    );
  }

  /// 构建情绪分布饼图
  /// Build emotion distribution pie chart
  Widget _buildEmotionDistributionChart(AnalyticsController controller) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '情绪分布',
            style: AppTextStyles.titleMedium,
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          SizedBox(
            height: 200,
            child: controller.emotionDistribution.isEmpty
                ? _buildEmptyChart('暂无分布数据')
                : Row(
                    children: [
                      Expanded(
                        flex: 2,
                        child: PieChart(
                          PieChartData(
                            sections: controller.emotionDistribution
                                .map((data) => PieChartSectionData(
                                      color: EmotionConstants.getEmotionColor(
                                        data.emotionType.value,
                                      ),
                                      value: data.percentage,
                                      title: '${data.percentage.toStringAsFixed(1)}%',
                                      radius: 60,
                                      titleStyle: AppTextStyles.bodySmall.copyWith(
                                        color: AppColors.onPrimary,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ))
                                .toList(),
                            sectionsSpace: 2,
                            centerSpaceRadius: 40,
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: controller.emotionDistribution
                              .map((data) => _buildLegendItem(
                                    EmotionConstants.getEmotionLabel(
                                      data.emotionType.value,
                                    ),
                                    EmotionConstants.getEmotionColor(
                                      data.emotionType.value,
                                    ),
                                    data.count,
                                  ))
                              .toList(),
                        ),
                      ),
                    ],
                  ),
          ),
        ],
      ),
    );
  }

  /// 构建强度分布图
  /// Build intensity distribution chart
  Widget _buildIntensityDistributionChart(AnalyticsController controller) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '强度分布',
            style: AppTextStyles.titleMedium,
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          SizedBox(
            height: 200,
            child: controller.intensityDistribution.isEmpty
                ? _buildEmptyChart('暂无强度数据')
                : BarChart(
                    BarChartData(
                      alignment: BarChartAlignment.spaceAround,
                      maxY: controller.intensityDistribution
                          .map((e) => e.count)
                          .reduce((a, b) => a > b ? a : b)
                          .toDouble(),
                      barTouchData: BarTouchData(
                        touchTooltipData: BarTouchTooltipData(
                          getTooltipColor: (group) => AppColors.surface,
                          getTooltipItem: (group, groupIndex, rod, rodIndex) {
                            return BarTooltipItem(
                              '强度 ${group.x + 1}\n${rod.toY.toInt()} 次',
                              AppTextStyles.bodySmall,
                            );
                          },
                        ),
                      ),
                      titlesData: FlTitlesData(
                        leftTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            getTitlesWidget: (value, meta) {
                              return Text(
                                value.toInt().toString(),
                                style: AppTextStyles.bodySmall.copyWith(
                                  color: AppColors.textSecondary,
                                ),
                              );
                            },
                          ),
                        ),
                        bottomTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            getTitlesWidget: (value, meta) {
                              return Text(
                                (value.toInt() + 1).toString(),
                                style: AppTextStyles.bodySmall.copyWith(
                                  color: AppColors.textSecondary,
                                ),
                              );
                            },
                          ),
                        ),
                        rightTitles: const AxisTitles(
                          sideTitles: SideTitles(showTitles: false),
                        ),
                        topTitles: const AxisTitles(
                          sideTitles: SideTitles(showTitles: false),
                        ),
                      ),
                      borderData: FlBorderData(
                        show: true,
                        border: Border.all(
                          color: AppColors.border,
                          width: 1,
                        ),
                      ),
                      barGroups: controller.intensityDistribution
                          .asMap()
                          .entries
                          .map((entry) => BarChartGroupData(
                                x: entry.key,
                                barRods: [
                                  BarChartRodData(
                                    toY: entry.value.count.toDouble(),
                                    color: AppColors.primary,
                                    width: 20,
                                    borderRadius: const BorderRadius.only(
                                      topLeft: Radius.circular(4),
                                      topRight: Radius.circular(4),
                                    ),
                                  ),
                                ],
                              ))
                          .toList(),
                    ),
                  ),
          ),
        ],
      ),
    );
  }

  /// 构建词云分析区域
  /// Build word cloud analysis section
  Widget _buildWordCloudSection(AnalyticsController controller) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '关键词分析',
            style: AppTextStyles.titleMedium,
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          controller.wordFrequencies.isEmpty
              ? _buildEmptyState('暂无关键词数据')
              : Wrap(
                  spacing: AppConstants.spacingSmall,
                  runSpacing: AppConstants.spacingSmall,
                  children: controller.wordFrequencies
                      .take(20)
                      .map((word) => _buildWordChip(word))
                      .toList(),
                ),
        ],
      ),
    );
  }

  /// 构建词汇芯片
  /// Build word chip
  Widget _buildWordChip(dynamic word) {
    final fontSize = (word.frequency / 10 * 8 + 12).clamp(12.0, 20.0);
    final opacity = (word.frequency / 10 * 0.8 + 0.2).clamp(0.2, 1.0);
    
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: AppConstants.paddingMedium,
        vertical: AppConstants.paddingSmall,
      ),
      decoration: BoxDecoration(
        color: AppColors.primary.withOpacity(opacity),
        borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
      ),
      child: Text(
        '${word.word} (${word.frequency})',
        style: AppTextStyles.bodyMedium.copyWith(
          fontSize: fontSize,
          color: AppColors.onPrimary,
          fontWeight: FontWeight.w600,
        ),
      ),
    );
  }

  /// 构建详细统计
  /// Build detailed statistics
  Widget _buildDetailedStatistics(AnalyticsController controller) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '详细统计',
            style: AppTextStyles.titleMedium,
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          _buildDetailRow('记录总数', '${controller.statisticsSummary?.totalRecords ?? 0} 条'),
          _buildDetailRow('本周记录', '${controller.statisticsSummary?.weekRecords ?? 0} 天'),
          _buildDetailRow('平均强度', '${(controller.statisticsSummary?.averageIntensity ?? 0.0).toStringAsFixed(1)}'),
          _buildDetailRow('最常见情绪', controller.statisticsSummary?.mostCommonEmotion ?? '无'),
          _buildDetailRow('最常见情绪次数', '${controller.statisticsSummary?.mostCommonEmotionCount ?? 0} 次'),
          _buildDetailRow('情绪趋势', controller.getEmotionTrend()),
        ],
      ),
    );
  }

  /// 构建详细统计行
  /// Build detail statistics row
  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: AppTextStyles.bodyMedium.copyWith(
              color: AppColors.textSecondary,
            ),
          ),
          Text(
            value,
            style: AppTextStyles.bodyMedium.copyWith(
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建图例项
  /// Build legend item
  Widget _buildLegendItem(String label, Color color, int count) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        children: [
          Container(
            width: 12,
            height: 12,
            decoration: BoxDecoration(
              color: color,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: AppConstants.spacingSmall),
          Expanded(
            child: Text(
              '$label ($count)',
              style: AppTextStyles.bodySmall,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建空图表
  /// Build empty chart
  Widget _buildEmptyChart(String message) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.insert_chart,
            size: 48,
            color: AppColors.textSecondary.withOpacity(0.5),
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          Text(
            message,
            style: AppTextStyles.bodyMedium.copyWith(
              color: AppColors.textSecondary,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建空状态
  /// Build empty state
  Widget _buildEmptyState(String message) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(AppConstants.paddingLarge),
      child: Column(
        children: [
          Icon(
            Icons.analytics_outlined,
            size: 48,
            color: AppColors.textSecondary.withOpacity(0.5),
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          Text(
            message,
            style: AppTextStyles.bodyMedium.copyWith(
              color: AppColors.textSecondary,
            ),
          ),
        ],
      ),
    );
  }
}